package com.nuonuo.router;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author duan
 * @version 1.0
 * @date 2023/4/7 9:43
 */
public class TrieRouteMatcher {

    TrieRouter tree = new TrieRouter();

    private final ReadWriteLock lock = new ReentrantReadWriteLock();
    private final Lock readLock = lock.readLock();
    private final Lock writeLock = lock.writeLock();

    public TrieRouteMatcher() {
    }

    public RouteInfo match(String target) {
        readLock.lock();
        try {
            return tree.match(target);
        } finally {
            readLock.unlock();
        }
    }

    public void addRoute(String path) {
        writeLock.lock();
        try {
            tree.addRoute(path);
        } finally {
            writeLock.unlock();
        }
    }

    public void delRoute(String path) {
        writeLock.lock();
        try {
            tree.delRoute(path);
        } finally {
            writeLock.unlock();
        }
    }

    public void updateRoute(String o, String n) {
        writeLock.lock();
        try {
            tree.updateRoute(o, n);
        } finally {
            writeLock.unlock();
        }
    }
}
